package com.example.leetcode.solution;

import java.util.Arrays;

public class Solution16 {

    public int threeSumClosest(int[] nums, int target) {
        int best = 10000000;
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if(i > 0 && nums[i - 1] == nums[i]){
                continue;
            }
            int j = i + 1, k = n - 1;
            while(j < k){
                int  sum = nums[i] + nums[j] + nums[k];
                // System.out.println(nums[i] +"+"+nums[j] +"+"+ nums[k] +"=" + sum);
                if( sum == target){
                    return sum;
                }
                // 根据差值的绝对值来更新答案
                if (Math.abs(sum - target) < Math.abs(best - target)) {
                    best = sum;
                }
                if (sum > target) {
                    int k0 = k -1;
                    while(j < k0 && nums[k0] == nums[k]){
                        k0--;
                    }
                    k = k0;
                }else{
                    int j0 = j +1;
                    while(j0 < k && nums[j0] == nums[j]){
                        j0++;
                    }
                    j = j0;
                }
            }
        }
        return best;
    }
}
